<?php include("siteTop.php"); ?>

<!--    
    Created By : Julian Ponce
    B.S. Computer Science - De La Salle Canlubang
    November 26, 2011
    Description :
    
    This page allows the admin to view the route details of a particular routeId.
-->
    
<?php 

    // THIS SERVES AS THE TEMPORARY ROUTE ID.
    $routeId = $_POST['routeId'];
   
    //CONNECT TO DATABASE
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // Start - Check Route if there is an ongoing main document
    function noOngoingRoute($routeId){
        $query = 
        "
            SELECT *
            FROM

                -- Connect the routeId by using RouteStep
                -- Get rows that are not Archived
                (SELECT DocLastStep.logId as logId, DocLastStep.stepId as stepId, DocLastStep.documentId as documentId, DocLastStep.activity as activity, RS.routeId as routeId
                FROM

                    -- Get the last step of the main document
                    (SELECT *
                    FROM 

                        -- Get the needed information of main document from the log
                        (SELECT L.logId as logId, L.stepId as stepId, L.documentId as documentId, L.activity as activity
                        FROM Log as L, MainDocument as MD, DocumentSetup as DS
                        WHERE L.documentId = MD.mainDocumentId AND MD.documentSetupId = DS.documentSetupId AND DS.type = 'MainDocument'
                        ORDER BY L.logId DESC) as MainDocs

                    GROUP BY documentId) as DocLastStep, RouteStep as RS

                WHERE DocLastStep.activity != 'Archived' AND RS.stepId = DocLastStep.stepId) as OngoingRoutes

            WHERE routeId = '$routeId'
        ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_fetch_array($result) == 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // Start - Check Route if there is an ongoing main document
    
    // Start - Check if the route has been routed
    function notYetRouted($routeId){
        $query = 
        "
            SELECT *
            FROM

                -- Connect the routeId by using RouteStep
                -- Get rows that are not Archived
                (SELECT DocLastStep.logId as logId, DocLastStep.stepId as stepId, DocLastStep.documentId as documentId, DocLastStep.activity as activity, RS.routeId as routeId
                FROM

                    -- Get the last step of the main document
                    (SELECT *
                    FROM 

                        -- Get the needed information of main document from the log
                        (SELECT L.logId as logId, L.stepId as stepId, L.documentId as documentId, L.activity as activity
                        FROM Log as L, MainDocument as MD, DocumentSetup as DS
                        WHERE L.documentId = MD.mainDocumentId AND MD.documentSetupId = DS.documentSetupId AND DS.type = 'MainDocument'
                        ORDER BY L.logId DESC) as MainDocs

                    GROUP BY documentId) as DocLastStep, RouteStep as RS

                WHERE RS.stepId = DocLastStep.stepId) as OngoingRoutes

            WHERE routeId = '$routeId'
        ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_fetch_array($result) == 0 ) {
            return true;
        }
        else {
            return false;
        }
    } // End - Check if the route has been routed
    
    // IDENTIFIES THE ROUTE DETAILS
    $query = 
        "
            SELECT *
            FROM DocumentRoute, DocumentSetup
            WHERE DocumentRoute.routeId = '$routeId' AND 
                  DocumentRoute.documentSetupId = DocumentSetup.documentSetupId
        ";
    
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    
    $routeName = $row['routeName'];
    $documentName = $row['documentName'];
    
?>
<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>

    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){
            prevImgClicked = "";
            
            
            jQuery(".stepInfoClass").hide();
            
            // THIS AJAX RETURNS ALL INFORMATION REGARDING ROUTE STEP OF
            // PARTICULAR ROUTE ID.
            jQuery.ajax({
                type : 'POST',
                url : 'ajaxRequests/admGetRouteDetails.php',
                dataType : 'json',
                data: {
                    routeId : "<?php echo $routeId; ?>"
                },
                success : function(data){
                    prevSubRouteId = "";
                    prevStepId = "";
                    circleCounter = 0;
                    
                    jQuery.each(data, function(index, data) {                            
                        if (prevSubRouteId != data.subRouteId) {
                            
                            
                            if (circleCounter == 1) {
                                jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_first").attr("src", "images/trackDoc/version5/single/grn_nothov_sngle.png");
                                jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_first").attr("id", "stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_single");
                            }
                            
                            else {
                                // CHANGE PREVIOUS IMAGE POSITION FROM CENTER TO LAST
                                jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_center").attr("src", "images/trackDoc/version5/last/grn_nothov_last.png");
                                jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_center").attr("id", "stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_last");
                            
                            }
                            
//                            // IF PREV SUBROUTE ID == NULL, PLACE CROSSROAD ICON
//                            if (prevSubRouteId == "NULL") {
//                                jQuery("#lastStep_NULL").before("<img src='images/trackDoc/horiz_line_thick.png' width='9' height='30'><img src='images/trackDoc/arrow_head.png' width='9' height='30'/><img src='images/trackDoc/cross_road.png' width='30px' height='30px'/>");
//                            }
//                            
//                            // IF PREV SUBROUTE ID != NULL, PLACE FINISH FLAG ICON
//                            else if (prevSubRouteId != "CANCELTRAC" && prevSubRouteId != "REJECTTRAC"){
//                                jQuery("#lastStep_"+prevSubRouteId).before("<img src='images/trackDoc/horiz_line_thick.png' width='9' height='30'><img src='images/trackDoc/arrow_head.png' width='9' height='30'/><img src='images/trackDoc/finish_flag.png' width='30px' height='30px'/>");
//                            }
                            
                            if (data.subRouteName == "NULL") {
                                data.subRouteName = "Initial Route";
                            }
                            
                            // FORMATION OF IMAGE -> stepIdImg_(stepId)_(subRouteId)_(Position)
                            
                            if (data.subRouteId == "CANCELTRAC" || data.subRouteId == "NULL" || data.subRouteId == "REJECTTRAC") {
                                jQuery("#lastRowDefault").before("<tr>" +
                                    "<td><input type='hidden' id='circleCount_"+data.subRouteId+"' value='0'/>"+data.subRouteName+"</td>"+
                                    "<td><img class='stepImageClass' id='stepIdImg_" + data.stepId + "_"+data.subRouteId+"_first' style='cursor:pointer;' src='images/trackDoc/version5/first/grn_nothov_frst.png' height='30px' width='30px'/><div id='lastStep_"+data.subRouteId+"'/></td>" +
                                    "</tr>");    
                            }
                            
                            else {
                                jQuery("#lastRowSubRoute").before("<tr>" +
                                    "<td><input type='hidden' id='circleCount_"+data.subRouteId+"' value='0'/>"+data.subRouteName+"</td>"+
                                    "<td><img class='stepImageClass' id='stepIdImg_" + data.stepId + "_"+data.subRouteId+"_first' style='cursor:pointer;' src='images/trackDoc/version5/first/grn_nothov_frst.png' height='30px' width='30px'/><div id='lastStep_"+data.subRouteId+"'/></td>" +
                                    "</tr>");
                            }
                            
                            
                            circleCounter = 1;
                            prevSubRouteId = data.subRouteId;
                        }
                        
                        else {
                            // FORMATION OF IMAGE -> stepIdImg_(stepId)_(subRouteId)_(Position)
                            jQuery("#lastStep_"+data.subRouteId).before("<img src='images/trackDoc/version5/line/line_drk_ornge.png' width='35' height='30'><img class='stepImageClass' id='stepIdImg_" + data.stepId + "_"+data.subRouteId+"_center' style='cursor:pointer;' src='images/trackDoc/version5/center/grn_nothov_cntr.png' height='30px' width='30px'/>");
                            circleCounter++;
                        }
                        prevStepId = data.stepId;
                    }); //[END] ITERATION OF ALL STEP ID's
                    
                    // FOR LAST CIRCLE.
                    if (circleCounter == 1) {
                        jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_first").attr("src", "images/trackDoc/version5/single/grn_nothov_sngle.png");
                        jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_first").attr("id", "stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_single");
                    }

                    else {
                        // CHANGE PREVIOUS IMAGE POSITION FROM CENTER TO LAST
                        jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_center").attr("src", "images/trackDoc/version5/last/grn_nothov_last.png");
                        jQuery("#stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_center").attr("id", "stepIdImg_"+prevStepId+"_"+prevSubRouteId+"_last");

                    }
                    
                },
                error : function() {
                    alert("fail in AJAX [admGetRouteDetails.php]");
                }
            });
            
            // [START]SHOW STEP INFORMATION WHEN IMAGE WAS CLICKED.
            jQuery(".stepImageClass").live("click",function() {
                
                // CHANGE PREVIOUS IMAGE YELLOW > GREEN (RETURN TO ORIGINAL)
                if (prevImgClicked != "") {
                    
                    subStr = prevImgClicked.split("_");
                    
                    // CHANGE CLICKED IMAGE BASED ON ITS POSITION (RETURN TO ORIGINAL).
                    switch (subStr[3]) {
                        case 'first' : imgUrl = "images/trackDoc/version5/first/grn_nothov_frst.png"; break;
                        case 'center' : imgUrl = "images/trackDoc/version5/center/grn_nothov_cntr.png"; break;
                        case 'last' : imgUrl = "images/trackDoc/version5/last/grn_nothov_last.png"; break;
                        case 'single' : imgUrl = "images/trackDoc/version5/single/grn_nothov_sngle.png"; break;
                    }
                    jQuery("#"+prevImgClicked).attr("src", imgUrl);
                }
                
                // SPLIT ID OF IMAGE TO GET stepId
                imgId = this.id;
                subStr = imgId.split("_");
                prevImgClicked = imgId;
                
                // THIS IS THE CLICKED STEP ID
                clickedStepId = subStr[1];
                
                // THIS IS THE CLICKED SUB ROUTE ID
                clickedSubRouteId = subStr[2];
                
                // THIS IS THE POSITION OF THE CIRCLE
                clickedCirclePos = subStr[3];
                
                // CHANGE CLICKED IMAGE BASED ON ITS POSITION.
                switch (clickedCirclePos) {
                    case 'first' : imgUrl = "images/trackDoc/version5/first/ylw_nothov_frst.png"; break;
                    case 'center' : imgUrl = "images/trackDoc/version5/center/ylw_nothov_cntr.png"; break;
                    case 'last' : imgUrl = "images/trackDoc/version5/last/ylw_nothov_last.png"; break;
                    case 'single' : imgUrl = "images/trackDoc/version5/single/ylw_nothov_sngle.png"; break;
                }
                jQuery("#"+imgId).attr("src", imgUrl);
                
                // AJAX IN GETTING STEP INFO.
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/admGetStepInfo.php',
                    dataType : 'json',
                    async : false,
                    data: {
                        stepId : clickedStepId
                    },
                    success : function(data){
                        if (data) {
                            
                            // REMOVE PREVIOUS STEP INFO CONTENT
                            jQuery("#stepInfoContent").remove();
                            
                            // ROLE SWITCH-CASE
                            switch(data.role){
                                case '1' : tempRole = "Sender"; break;
                                case '2' : tempRole = "Approve/Return for Revisions/Disapprove"; break;
                                case '3' : tempRole = "Archiver"; break;    
                            }
                            
                            // SUBSTITUTE CAN BE CANCELLED (YES/NO)
                            if (data.canBeCancelled == "1") {
                                tempCancel = "Yes";
                            }
                            
                            else {
                                tempCancel = "No";
                            }
                            
                            // CHECKS IF subRouteName == NULL, if YES, change it to "Initial Route"
                            if (data.subRouteName == "NULL") {
                                data.subRouteName = "Initial Route";
                            }
                            
                            jQuery("#stepInfoTable").append("<tr id='stepInfoContent'>"+
                                "<td>" +
                                    "<table id='innerTable' border='0' style='border-top-style:none;'>" +
                                        "<tr>" +
                                            "<td width='50%'>" +
                                                "<table id='tableInfo1' border='0' style='border-top-style:none;'>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>Step Number : </b></td><td width='50%' valign='top'>"+data.stepNumber+"</td>" +
                                                    "</tr>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>Sub Route Name : </b></td><td width='50%' valign='top'>"+data.subRouteName+"</td>" +
                                                    "</tr>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>Category : </b></td><td width='50%' valign='top'>"+data.category+"</td>" +
                                                    "</tr>" +
                                                "</table>" +
                                            "</td>" +
                                            "<td width='50%'>" +
                                                "<table id='tableInfo2' border='0' style='border-top-style:none;'>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>Recipient Role : </b></td><td width='50%' valign='top'>"+tempRole+"</td>" +
                                                    "</tr>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>Transaction Can Be Cancelled : </b></td><td width='50%' valign='top'>"+tempCancel+"</td>" +
                                                    "</tr>" +
                                                    "<tr>" +
                                                        "<td width='50%' valign='top'><b>User Activity : </b></td><td width='50%' valign='top'>"+data.userActivity+"</td>" +
                                                    "</tr>" +
                                                "</table>" +
                                            "</td>" +
                                        "</tr>" +
                                        "<tr>" +
                                            "<td valign='top'>" +
                                                "<span class='screenlet' style='text-align:center;padding-left : 0; padding-right : 0; padding-top : 0;width:100%' >Required Attachments</span>"+
                                                "<table id='reqAttachTable' style='padding-left : 0; padding-right : 0; padding-top : 0;width:100%'>" +
                                                "</table>" +
                                            "</td>" +
                                            "<td valign='top'>" +
                                                "<span class='screenlet' style='text-align:center;padding-left : 0; padding-right : 0; padding-top : 0;width:100%' >Recipient</span>"+
                                                "<table id='recipientsTable' style='padding-left : 0; padding-right : 0; padding-top : 0;width:100%'>" +
                                                "</table>" +
                                            "</td>" +
                                        "</tr>" +
                                    "</table>" +
                                "</td>" +
                            "</tr>");
                        
                            // [START] GET RECIPIENTS IN A STEP
                            jQuery.ajax({
                                type : 'POST',
                                url : 'ajaxRequests/admGetRecipients.php',
                                dataType : 'json',
                                async : false,
                                data: {
                                    stepId : clickedStepId
                                },
                                success : function(data){
                                    jQuery.each(data, function(index, data) {                            
                                        jQuery("#recipientsTable").append("<tr><td>"+data.recipientDeptPosName+"</td></tr>");
                                    });                  
                                },
                                error : function() {
                                    alert("fail in AJAX [admGetRecipients.php]");
                                }
                            });
                            // [END] GET RECIPIENTS IN A STEP
                        
                            // [START] GET REQUIRED ATTACHMENTS IN A STEP
                            jQuery.ajax({
                                type : 'POST',
                                url : 'ajaxRequests/admGetReqAttachments.php',
                                dataType : 'json',
                                async : false,
                                data: {
                                    stepId : clickedStepId
                                },
                                success : function(data){
                                    // THERE ARE ATTACHMENTS FOR THIS STEP.
                                    if (data) {
                                        jQuery.each(data, function(index, data) {                            
                                            jQuery("#reqAttachTable").append("<tr><td>"+data.documentName+"</td></tr>");
                                        });  
                                    }
                                    
                                    // NO ATTACHMENTS FOR THIS STEP
                                    else {
                                        jQuery("#reqAttachTable").append("<tr><td>No required attachment for this step.</td></tr>");
                                    }
                                                 
                                },
                                error : function() {
                                    alert("fail in AJAX [admGetReqAttachments.php]");
                                }
                            });
                            // [END] GET REQUIRED ATTACHMENTS IN A STEP
                            
                            
                        
                            jQuery(".stepInfoClass").show();
                            jQuery("#initialMsgSpan").hide();
                        }
                    },
                    error : function() {
                        alert("fail");
                    }
                });
                
            }); // [END]SHOW STEP INFORMATION WHEN IMAGE WAS CLICKED.
            
            // [START] IMG HOVER, THEN SHOW POSITIONS TO RECEIVE.
            jQuery(".stepImageClass").live({
                mouseover: function(mousePtr) {
                    // HOVER IN CODES ------------------
                    imgId = this.id;
                    subStr = imgId.split("_");
                    
                    // STEP ID.
                    hoverStepId = subStr[1];
                    
                    // [START] GET RECIPIENTS IN A STEP
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admGetRecipients.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            stepId : hoverStepId
                        },
                        success : function(data){
                            
                            setInfo = "<table id='hoverTable' style='border:0; margin-bottom:0px;'>";
                            
                            // ITERATION OF ALL POSITIONS
                            jQuery.each(data, function(index, data) {                            
                                setInfo += "<tr><td>"+data.recipientDeptPosName+"</td></tr>";
                            });                  
                            setInfo += "</table>";
                            // PUT THE INFORMATION IN THE DIV
                            jQuery(".stepInvisibleInfo").html(setInfo);
                        },
                        error : function() {
                            alert("fail in AJAX [admGetRecipients.php]");
                        }
                    });
                    // [END] GET RECIPIENTS IN A STEP
                   
                    // MODIFY THE POSITION SO THAT IT IS NOT THAT FAR FROM THE CIRCLE
                    topValue = mousePtr.pageY - 10;
                    leftValue = mousePtr.pageX - 130;
                   
                    // MODIFY THE CSS POSITION BEFORE SHOWING
                    jQuery(".stepInvisibleInfo").css({ 'display': 'none', 'top': topValue, 'left': leftValue });
                    jQuery(".stepInvisibleInfo").show();
                   
                }, 
                mouseout: function() {
                    // HOVER OUT CODES -----------------
                    jQuery(".stepInvisibleInfo").hide();
                }
            }); // END - JQUERUES FOR SHOWING INFORMATION
            
            // [START] BACK BUTTON CLICKED > REDIRECT TO admRouteSetup.php
            jQuery("#backButton").click(function() {
                    window.location = 'admRouteSetup.php';                
            });
            
            // Start - Go to admRouteEdit.php
            jQuery('#editButton').live("click",function() {
                jQuery("#routeEditForm").submit();
            }); // End - Go back to admRouteEdit.php 
            
            // Start - Ajax in deleting a route
            jQuery('#deleteButton').live("click",function() {
                var contEdit = confirm("Do you really want to delete this route?");
                
                if ( contEdit == true ) {
                    // Start - Ajax for deleting a route 
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admRouteDelete.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            routeId : jQuery("#routeId").val()
                        },
                        success : function(data){
                            if (data) {
                                if ( data[0].flag == "success" ) {
                                    jQuery("#routeSuccessMessage").val(data[0].msg);
                                    jQuery("#routeStpMsgForm").submit();
                                }
                                else {
                                    alert(data[0].msg);
                                }
                            }
                        },
                        error : function() {
                            alert("Error : Deleting the route was not successful.");
                        }
                    }); // End - Ajax for deleting a route
                } // End if
            }); // End - Ajax in deleting a route 
            
        }); // END - (DOCUMENT READY FUNCTION)
    </script>
    <!-- HEAD END -->


<?php include("siteMiddle.php"); ?>
    
<!-- START OF BODY -->
<div id="content">
    <div class="stepInvisibleInfo"></div>
    <h1>Route View Page</h1>
  
        <span class="screenlet" >Routes in <?php echo $routeName; ?></span>
        <table border="1">
            <tr>
                <th>Sub Route Name</th>
                <th>Sub Route Steps</th>
            </tr>
            <tr id ="lastRowDefault"/>
            <tr id ="lastRowSubRoute"/>
        </table>
        
        <span class="screenlet stepInfoClass">Step Information</span>
        <table id="stepInfoTable" class="stepInfoClass">
        </table>

    <span id="initialMsgSpan">Click on the image to view step information.<BR><BR></span>  
    
    <?php
        if ( noOngoingRoute($routeId) == true ) {
            // Route can only be edited if there is no currently ongoing route.
            // It can be edited if it is newly created, or all of its main document are Archived
            ?>
                <!-- EDIT BUTTON -->
                <input type="Button" name="editButton" id="editButton" class="siteGreenButton" value="Edit"/>
            <?php
        }
    
        if ( notYetRouted($routeId) == true ) {
            ?>
                <!-- DELETE BUTTON -->
                <input type="Button" name="deleteButton" id="deleteButton" class="siteRedButton" value="Delete"/>
            <?php
        }
    ?>
                
    
    
    <!-- BACK BUTTON -->
    <input type="Button" name="backButton" id="backButton" class="siteGreenButton" value="Back"/>
    
    <!-- THIS WILL SERVE AS THE FORM IN ORDER TO PASS userId TO admAccountEdit.php -->    
    <form id="routeEditForm" action="admRouteEdit.php" method="POST">
        <input type="hidden" name="routeId" id="routeId"value="<?php echo $routeId; ?>"/>
    </form>
    
    <!-- Hidden form to be used when the deleting of route was successful -->
    <form id="routeStpMsgForm" name="routeStpMsgForm" action="admRouteSetup.php" method="POST">
        <input type="hidden" name="routeSuccessMessage" id="routeSuccessMessage" value=""/>
    </form>

</div> 


<!-- BODY END -->
<?php 
    include ("siteBottom.php"); 
?>